package com.qc.wintrax;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
import com.qc.wintrax.db.DaoMaster;
import com.qc.wintrax.db.DaoSession;
import com.qc.wintrax.db.HBDevOpenHelper;
import com.qc.wintrax.utils.LogUtil;
import com.qc.wintrax.utils.XMLRequest;

import java.util.ArrayList;
import java.util.List;

import greendao.MapInfo;

/**
 * Created by asus on 2016/8/3.
 */
public class WTApplication  extends Application{
    private Object nowPageContext = null;
    private Activity nowActivity = null;
    private static Context sContext;
    public final static String CONFIG = "config";
    private ArrayList<Activity> activityList = new ArrayList<Activity>();
    //初始化默认TAG
    public static final String TAG = "WTTag";
    private RequestQueue mRequestQueue;
    private static WTApplication sInstance;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    private List<MapInfo>  infoList;
    private List<Double>  altList;

    @Override
    public void onCreate() {
        super.onCreate();
        initContext();
        InitImageLoader();
        sInstance = this;
//        SMSSDK.initSDK(this, "10b8241ff68f4", "cca70464adb6f717db4ed261cda1e4b0");
//
//        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
//        JPushInterface.init(this);            // 初始化 JPush
    }

    public List<MapInfo> getInfoList() {
        return infoList;
    }

    public void setInfoList(List<MapInfo> infoList) {
        this.infoList = infoList;
    }

    public List<Double> getAltList() {
        return altList;
    }

    public void setAltList(List<Double> altList) {
        this.altList = altList;
    }

    /**
     * 取得DaoMaster
     * <p/>
     * context
     *
     * @return
     */
    public static DaoMaster getGSDaoMaster() {
        if (daoMaster == null) {
            HBDevOpenHelper helper = new HBDevOpenHelper(sInstance, "HB_db", null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 取得DaoSession
     * <p/>
     * context
     *
     * @return
     */
    public static DaoSession getGSDaoSession() {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getGSDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    public static synchronized WTApplication getInstance() {
        return sInstance;
    }

    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }


    /**
     * @author xbd
     * @Description:(添加网络请求到队列) create at 2016/3/21 10:24
     **/
    public <T> void addToRequestQueue(Request<T> req, XMLRequest tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty((CharSequence) tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    /**
     * @author xbd
     * @Description:(添加网络请求到队列) create at 2016/3/21 10:24
     **/
    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * @author xbd
     * @Description:(通过tag取消所有网络请求) create at 2016/3/21 10:25
     **/
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

    /**
     * @author xbd
     * @Description:(通过默认的TAG，取消所有网络请求) create at 2016/3/21 10:25
     **/
    public void cancelAllRequests() {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(TAG);
        }
    }

    public static Context getContext() {
        return sContext;
    }

    private void initContext() {
        sContext = getApplicationContext();
    }

    /**
     * @param activity
     * @throws
     * @Title: setOnActivityCreate
     * @Description: TODO(com.gesee.huiba.activity 创建)
     * @author xbd
     */
    public void setOnActivityCreate(Activity activity) {
        if (null == activityList) {
            activityList = new ArrayList<Activity>();
        }
        activityList.add(0, activity);
        setCurrentActivity(activity);
        setNowPageContext(activity);
    }

    /**
     * @param activity
     * @throws
     * @Title: setOnActivityDestroy
     * @Description: TODO(com.gesee.huiba.activity 销毁)
     * @author xbd
     */
    public void setOnActivityDestroy(Activity activity) {
        if (null != activityList && activityList.size() > 0) {
            activityList.remove(activity);
            setCurrentActivity();
        }
    }

    /**
     * com.gesee.huiba.activity Resume
     *
     * @param activity
     */
    public void setOnActivityResume(Activity activity) {
        setCurrentActivity(activity);
        setNowPageContext(activity);

    }

    /**
     * com.gesee.huiba.fragment Resume
     *
     * @param fragment
     */
    public void setOnFragmentResume(Fragment fragment) {
        setNowPageContext(fragment);
    }

    /**
     * @throws
     * @Title: setCurrentActivity
     * @Description: TODO(设置当前的activity)
     * @author xbd
     */
    private void setCurrentActivity() {
        if (null != activityList && activityList.size() > 0) {
            nowActivity = activityList.get(0);
        }
    }

    /**
     * @param activity
     * @throws
     * @Title: setCurrentActivity
     * @Description: TODO(设置当前的activity)
     * @author xbd
     */
    private void setCurrentActivity(Activity activity) {
        nowActivity = activity;
    }

    public void finishAllActivity() {
        int size = activityList.size();
        for (int i = 0; i < size; i++) {
            Activity activity = getCurrentActivity();
            activity.finish();
            WTApplication.getInstance().setOnActivityDestroy(activity);
        }
        activityList.clear();
    }

    public void finishActivity() {
        finishActivity(1);
    }

    public void finishActivity(int count) {
        if (count > getActivitysCount()) {
            LogUtil.e("finishActivity params count is error");
            return;
        }
        for (int i = 0; i < count; i++) {
            Activity activity = activityList.get(i);
            LogUtil.i("finishActivity is : 【" + activity.getComponentName() + "】");
            activity.finish();
            WTApplication.getInstance().setOnActivityDestroy(activity);
        }
    }

    public void finishActivity(List<Class<?>> activityClassList) {
        List<Activity> templist = new ArrayList<Activity>();
        for (Class<?> activityClass : activityClassList) {
            for (Activity mActivity : activityList) {
                if (mActivity.getClass().equals(activityClass)) {
                    templist.add(mActivity);
                }
            }
        }

        for (Activity tempActivity : templist) {
            activityList.remove(tempActivity);
            tempActivity.finish();
        }
    }

    /**
     * @param activity
     * @throws
     * @Title: finishActivity
     * @Description: TODO(结束指定Activity)
     * @author xbd
     */
    public void finishActivity(Activity activity) {
        if (activity != null && activityList.contains(activity)) {
            activityList.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * @param cls
     * @throws
     * @Title: finishActivity
     * @Description: TODO(结束指定类名的Activity)
     * @author xbd
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityList) {
            if (activity.getClass().equals(cls)) {
                activityList.remove(activity);
            }
        }
    }

    /**
     * @return
     * @throws
     * @Title: getCurrentActivity
     * @Description: TODO(获取当前activity)
     * @author xbd
     */
    public Activity getCurrentActivity() {
        int size = activityList.size();
        LogUtil.d("currentActivity is : 【" + nowActivity.getComponentName() + "】  com.gesee.huiba.activity count : 【" + size + "】");
        for (int i = 0; i < size; i++) {
            LogUtil.d("com.gesee.huiba.activity stack position " + i + ": com.gesee.huiba.activity = " + activityList.get(i).getComponentName());
        }
        LogUtil.d("currentActivity: " + nowActivity.getComponentName() + " com.gesee.huiba.activity in the list of position: 【" + activityList.indexOf(this.nowActivity) + "】");
        return this.nowActivity;
    }

    /**
     * @return
     * @throws
     * @Title: getPreActivity
     * @Description: TODO(获取上一个activity)
     * @author xbd
     */
    public Activity getPreActivity() {
        if (activityList.size() == 1) {
            return null;
        }
        return activityList.get(activityList.size() - 2);
    }

    /**
     * @param mActivity
     * @return
     * @throws
     * @Title: getActivity
     * @Description: TODO(根据activityName获取activity)
     * @author xbd
     */
    @SuppressWarnings("unchecked")
    public Class<? extends Activity> getActivity(Class<? extends Activity> mActivity) {
        if (activityList.size() == 0) {
            return mActivity;
        }
        if (activityList.contains(mActivity)) {
            for (Activity activityItem : activityList) {
                if (activityItem.getComponentName().equals(mActivity.getName())) {
                    mActivity = (Class<Activity>) activityItem.getClass();
                    break;
                }
            }
        }
        return mActivity;
    }

    /**
     * @return
     * @throws
     * @Title: getActivitysCount
     * @Description: TODO(返回 com.gesee.huiba.activity 总数)
     * @author xbd
     */
    public int getActivitysCount() {
        return activityList.size();
    }

    public Object getNowPageContext() {
        return nowPageContext;
    }

    public void setNowPageContext(Object nowPageContext) {
        this.nowPageContext = nowPageContext;
    }

//    public static HBApplication getInstance()
//    {
//        return instance;
//    }

    /**
     * @param key
     * @param value
     * @throws
     * @Title: setConfig
     * @Description: TODO(配置参数的key.配置参数的值)
     * @author xbd
     */
    public void setConfig(String key, String value) {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(CONFIG, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        LogUtil.d("editConfig : key = " + key + " , value = " + value);
        editor.commit();
    }

    /**
     * @param key
     * @return
     * @throws
     * @Title: getConfig
     * @Description: TODO(配置参数的key)
     * @author xbd
     */
    public String getConfig(String key) {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(CONFIG, MODE_PRIVATE);
        String orderId = sharedPreferences.getString(key, "null");
        LogUtil.d("readConfig : key = " + key + " , value = " + sharedPreferences.getString(key, ""));
        return orderId;
    }

    private void InitImageLoader() {

        // This configuration tuning is custom. You can tune every option, you
//        // may tune some of them,
//        // or you can create default configuration by
//        // ImageLoaderConfiguration.createDefault(this);
//        // method.
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator()).diskCacheSize(50 * 1024 * 1024) // 50
//                // Mb
//                .tasksProcessingOrder(QueueProcessingType.LIFO).writeDebugLogs() // Remove
//                // for
//                // release
//                // app
//                .build();
//        // Initialize ImageLoader with configuration.
//
//        ImageLoader.getInstance().init(config);
    }

}
